#include "stdafx.h"
#include "objMgr_t.h"
#include "runtimeclass.h"
#include "threadSyncIDMaker_t.h"

BaseObject* objMgr_t::create(const string & className, UniqueID uid, UniqueID parent)
{
	BaseObject* newObj = RuntimeClass::CreateObject(className);
	if (newObj==NULL){return NULL;}

	if (uid.IsNull())
	{
		int id = tmIDMaker->NewID();
		uid.m_id = id;
	}

	objMap::iterator iter;
	iter = objs.find(uid);
	if (iter==objs.end())
	{
		objs.insert(make_pair(uid,newObj));
		newObj->setUID(uid);
		if (!parent.IsNull())
			newObj->setParent(parent);
		newObj->setScript(className);
		return newObj;
	}
	
	return NULL;
}


bool objMgr_t::destroy(UniqueID uid)
{
	objMap::iterator iter;
	iter = objs.find(uid);
	if (iter!=objs.end())
	{
		safe_delete(iter->second);
		tmIDMaker->RemoveID(uid.m_id);
		objs.erase(iter);
		return true;
	}
	return false;
}


BaseObject* objMgr_t::getObj(UniqueID uid)
{
	objMap::iterator iter;
	iter = objs.find(uid);
	if (iter!=objs.end())
	{
		return iter->second;
	}
	return NULL;
}


vector<UniqueID> objMgr_t::getObjs()
{
	vector<UniqueID> uids;
	objMap::iterator iter;
	for ( iter=objs.begin(); iter!=objs.end(); iter++)
	{
		uids.push_back(iter->first);
	}
	return uids;
}	


void objMgr_t::destroyAll()
{
	objMap::iterator iter;
	for ( iter=objs.begin(); iter!=objs.end(); iter++)
	{
		tmIDMaker->RemoveID(iter->first.m_id);
		safe_delete(iter->second);
	}
	objs.clear();
}